package com.sandbox.search;

import org.apache.commons.cli.*;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;

public class IndexBuilder {
    public static void main(String[] args) throws ParseException, IOException {
        Options options = new Options();
        options.addOption("i", true, "input data directory (full path)");
        options.addOption("o", true, "output index directory (full path)");
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);
        String inputDir = cmd.getOptionValue("i");
        String outputDir = cmd.getOptionValue("o");

        Directory indexDir = FSDirectory.open(new File(outputDir));
        IndexWriterConfig config = new IndexWriterConfig(SearchConstants.CURRENT_LUCENE_VERSION,
                new StandardAnalyzer(SearchConstants.CURRENT_LUCENE_VERSION));
        IndexWriter indexFileWriter = new IndexWriter(indexDir, config);

        for (File fileToIndex : new File(inputDir).listFiles()) {
            System.out.println("Adding " + fileToIndex.getName());
            Document doc = new Document();
            doc.add(new Field(SearchConstants.FILENAME, fileToIndex.getName(), Field.Store.YES, Field.Index.ANALYZED,
                    Field.TermVector.WITH_POSITIONS_OFFSETS));
            doc.add(new Field(SearchConstants.BODY, FileUtils.readFileToString(fileToIndex), Field.Store.YES,
                    Field.Index.ANALYZED));
            indexFileWriter.addDocument(doc);
        }

        indexFileWriter.close();
    }
}
